import { getUserCenter } from '@/api/user'
import { TOKEN_KEY } from '@/enums/cacheEnums'
import cache from '@/utils/cache'
import { defineStore } from 'pinia'
import { getImInfoAPI } from '@/api/my'
import { TUILogin } from '@tencentcloud/tui-core'
import ChatUikitEngine from '@tencentcloud/chat-uikit-engine'

export interface UserSate {
    userInfo: IUserInfo

    token: string | null
    temToken: string | null
    imInfo: any
}

export const useUserStore = defineStore({
    id: 'userStore',
    state: (): UserSate => ({
        userInfo: uni.getStorageSync('userInfo') || {},
        token: cache.get(TOKEN_KEY) || null,
        temToken: null,
        imInfo: null
    }),
    getters: {
        isLogin: (state) => !!state.token,
        isBind(): boolean {
            const info = this.userInfo as IUserInfo
            // 是否绑定邀请人
            return !!(info.appUser && info.appUser.inviteId)
        },
        // 是否为服务商
        isService() {
            const info = this.userInfo as IUserInfo
            return info.roles && info.roles.length > 1 && info.appUser.currentRoleId == '2'
        },
        // 普通用户
        isNormal() {
            const info = this.userInfo as IUserInfo
            return info.appUser.currentRoleId == '1'
        },
        // 当前用户身份
        getCurrentRole() {
            const info = this.userInfo as IUserInfo

            return info.appUser && info.appUser.currentRoleId
        },
        // 邀请码
        invitationCode() {
            const info = this.userInfo as IUserInfo

            return info.appUser && info.appUser.invitationCode
        },
        // 用户信息
        AppUser() {
            const info = this.userInfo as IUserInfo

            return info.appUser
        },
        // 邀请人id
        inviteId() {
            const info = this.userInfo as IUserInfo

            return info.appUser && info.appUser.inviteId
        }
    },
    actions: {
        // 获取im信息
        async getImInfo() {
            try {
                const res = await getImInfoAPI()
                if (res.code === 0) {
                    this.imInfo = res.data

                    console.log('this.imInfo', this.imInfo)
                }
            } catch (err) {
                // uni.showToast({
                //     title: err,
                //     icon: 'none'
                // })
            }
        },

        async getUser() {
            const { data, ok } = await getUserCenter()
            this.userInfo = data.appUser

            uni.setStorageSync('userInfo', data.appUser)
        },
        login(token: string) {
            this.token = token
            cache.set(TOKEN_KEY, token)
        },
        logout() {
            this.token = ''
            this.userInfo = {}

            uni.removeStorageSync('userInfo')
            cache.remove(TOKEN_KEY)
            // im退出登录
            if (ChatUikitEngine.isReady()) {
                TUILogin.logout()
            }
        }
    }
})
